import java.io.*;
import java.net.Socket;
import java.util.Scanner;


public class ChatClient {
    Scanner sc;
    ObjectOutputStream oos;
    ObjectInputStream ois;
    public ChatClient(){
        try {
            Socket socket = new Socket("localhost",9900);
            //提示用户输入姓名并处理用户在控制台输入的姓名
            recNameAndEchoHello(socket);
            while (true){
                String msg =sc.nextLine();
                oos.writeObject(msg);

                System.out.println(ois.readObject());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private void recNameAndEchoHello(Socket socket) throws IOException, ClassNotFoundException {
        System.out.println("请输入您的姓名:");
        //使用Scanner实现从控制台输入
        sc = new Scanner(System.in);
        String name = sc.nextLine();

        //获得与服务器端通信的输出流对象，并向服务器端发送姓名
        OutputStream os = socket.getOutputStream();
        oos = new ObjectOutputStream(os);
        oos.writeObject(name);

        //接收服务器端的消息并在控制台输出
        InputStream is = socket.getInputStream();
        ois = new ObjectInputStream(is);
        System.out.println(ois.readObject());
    }

    public static void main(String[] args) {
        new ChatClient();
    }
}
